package com.lionxing.DNTG;

import java.util.ArrayList;

import org.cocos2d.actions.base.CCAction;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteFrame;
import org.cocos2d.nodes.CCTextureCache;
import org.cocos2d.opengl.CCTexture2D;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGRect;
import org.cocos2d.types.CGSize;

import android.R.bool;

public class Box {

	CGSize size;
	ArrayList<ArrayList<Tile>> content;
	ArrayList<Tile> readyToRemoveTiles;
	boolean lock;
	CCSprite layer;
	Tile OutBorderTile;
	int imgValue;
	ArrayList<Tile> removetitle;
	
	public Box  (CGSize aSize)
	{
		size = aSize;
		OutBorderTile = new Tile(-1, -1);
		content = new ArrayList<ArrayList<Tile>>(20);
		
		readyToRemoveTiles = new ArrayList<Tile>(40);
		
		for (int y=0; y<size.height; y++) {
		
	       // NSLog(@"yyyy == %d",y);
			ArrayList<Tile>  rowContent = new ArrayList<Tile>((int)size.width);
			for (int x=0; x < size.width; x++) {
	        
				Tile tile = new Tile(x, y);
				rowContent.add(tile);
				readyToRemoveTiles.add(tile);
	            tile.x0 = x;
	            tile.y0 = y;
	            tile.x = x;
	            tile.y = y;

	            
	           // NSLog(@"xxxx= %d",x);
			}
			
			
			content.add(rowContent);

		}
			    
	    removetitle = new ArrayList<Tile>((int)size.height * (int)size.width);

	}
	
	public Tile getTile(int x, int y)
	{
		if (x < 0 || x >= GameDefine.kBoxWidth || y < 0 || y >= GameDefine.kBoxHeight) {
			return OutBorderTile;
		}
		//return [[content objectAtIndex: y] objectAtIndex: x];
		
		return content.get(y).get(x);
	}
	
	private void removetitle ()
	{
	    if (removetitle != null && removetitle.size() > 0) {
	        
	        
	        
	        while (removetitle.size() > 0) {
	            
	            
	            
	            
	            //Tile * a = [removetitle objectAtIndex:0];
	            Tile a = removetitle.get(0);
	            
	           // Tile* b = [removetitle objectAtIndex:[removetitle count]-1];
	            Tile b = removetitle.get(removetitle.size() -1);
	            
//	            CCAction *actionA = [CCSequence actions:
//	                                 [CCMoveTo actionWithDuration:kMoveTileTime position:b.sprite.position],
//	                                 nil
//	                                 ];
//	            
//	            CCMoveTo actionToA =  CCMoveTo.action(GameDefine.kMoveTileTime, b.sprite.getPosition());
//	            
//	            
//	            
//	           // CCAction  actionA=   CCSequence.actions(actionToA);
//	            
//	            CCMoveTo actionToB =  CCMoveTo.action(GameDefine.kMoveTileTime, a.sprite.getPosition());
//	            
	            
	            
	            //CCAction  actionB=   CCSequence.actions(actionToB);
	           // a.sprite.runAction(actionToA);
	            //b.sprite.runAction(actionToB);
	            
	            CGPoint tmp =     a.sprite.getPosition();
	            a.sprite.setPosition(b.sprite.getPosition());
	            b.sprite.setPosition(tmp);
	            
	            a.trade(b);
	            
	            removetitle.remove(a);
	            removetitle.remove(b);
	        }
	    }

	}


	Boolean check(int picnum)
	{
		
		//NSArray *objects = [[readyToRemoveTiles objectEnumerator] allObjects];
		if ( readyToRemoveTiles.size() == 0) {
			return false;
		}
		
		int countTile = readyToRemoveTiles.size();
		for (int i=0; i<countTile; i++) {
//			Tile  tile = readyToRemoveTiles.get(i);
//			if (tile.value == 0) {
//				//[readyToRemoveTiles addObject:tile];
//				readyToRemoveTiles.add(tile);
//				continue;
//			}
//			
//			tile.value = 0;
//			if (tile.sprite != null) {
//				//[layer removeChild: tile.sprite cleanup:YES];
//				
//				layer.removeChild(tile.sprite, true);
//			}
		}

		//[readyToRemoveTiles removeAllObjects];
	    readyToRemoveTiles.clear();
		imgValue = picnum;
		//NSString *name = [NSString stringWithFormat:@"%d.jpg",picnum];
		String name = String.format("%d.png", picnum);
	    //NSString * name = @"1.jpg";
		//CCTexture2D  texture = [[CCTextureCache sharedTextureCache] addImage:name];
		
		CCTexture2D texture = CCTextureCache.sharedTextureCache().addImage(name);
		
		//CCSprite sp = CCSprite.sprite(filename)
		
		//NSMutableArray *imgFrames = [NSMutableArray array];
		
		ArrayList<CCSpriteFrame> imgFrames = new ArrayList<CCSpriteFrame>(30);
		//[imgFrames removeAllObjects];
		imgFrames.clear();
		for (int i = 0; i < GameDefine.kBoxWidth; i++) {
			for (int j = GameDefine.kBoxHeight -1; j >= 0; j--) {
//				CCSpriteFrame *imgFrame = [CCSpriteFrame frameWithTexture:texture rect:CGRectMake(i*100, j*100, 100, 100) offset:CGPointZero];
	            
	           // CCSpriteFrame* imgFrame = [CCSpriteFrame frameWithTexture:texture rect:CGRectMake(i*100, j*100, 100, 100)];
				//[imgFrames addObject:imgFrame];
				
				CCSpriteFrame imgFrame = CCSpriteFrame.frame(texture, CGRect.make(i*100, j*100, 100, 100),CGPoint.zero());
				imgFrames.add(imgFrame);
			}
		}
		
		/*
		NSUInteger count = [imgFrames count];
	    for (NSUInteger i = 0; i < count; ++i) {
	        // Select a random element between i and end of array to swap with.
	        int nElements = count - i;
	        int n = (arc4random() % nElements) + i;
	        [imgFrames exchangeObjectAtIndex:i withObjectAtIndex:n];
	    }
		*/
		
		for (int x=0; x<size.width; x++) {
			int extension = 0;
			for (int y=0; y<size.height; y++) {
				//Tile tile = [self objectAtX:x Y:y];
	            Tile tile = this.getTile(x,y);
	           
				if(tile.value == 0){
					extension++;
				}else if (extension == 0) {
					
				}
			}
	        //NSLog(@"extension count = %d",extension);
					
			for (int i=0; i<extension; i++) {
				//Tile destTile = [self objectAtX:x Y:kBoxHeight-extension+i];
				Tile destTile = this.getTile(x, GameDefine.kBoxHeight -extension +i);
				CCSpriteFrame img = imgFrames.get(0);
				//CCSprite sprite = [CCSprite spriteWithSpriteFrame:img];
				CCSprite sprite = CCSprite.sprite(img);
				
				//[imgFrames removeObjectIdenticalTo:img];
				imgFrames.remove(img);
				sprite.setPosition(CGPoint.make(GameDefine.kStartX + x * GameDefine.kTileSize + GameDefine.kTileSize/2, GameDefine.kStartY + (GameDefine.kBoxHeight + i) * GameDefine.kTileSize + GameDefine.kTileSize/2 - GameDefine.kTileSize * extension));
				//[layer addChild: sprite];
				layer.addChild(sprite);
				

				destTile.value = (4* destTile.x) + destTile.y;
				destTile.originalValue = destTile.value;
				destTile.sprite = sprite;
				
				//NSLog(@"postion x = %f y = %f",sprite.position.x , sprite.position.y);
	            //[removetitle addObject:destTile];
				removetitle.add(destTile);
				
			}
	        
			//return true;
		}
	    
	    //[self removetitle];
		
		 this.removetitle();
		return true;
	}


	boolean checkSolution () {
		
		boolean isSolved = true;
		
		for (int x=0; x<size.width; x++) {
			for (int y=0; y<size.height; y++) {
				Tile tile = this.getTile(x, y);
				
				if (tile.originalValue != tile.value) {
					isSolved = false;
				}
			}
		}
		
		if (isSolved) {
			//NSLog(@"The Sliding Image is Solved");
			return true;
		} else {
			//NSLog(@"The Sliding Image is NOT Solved");
			return false;
		}	
		
		//return true;
	}

	
	public void setLock(boolean abool)
	{
		
		lock = abool;
		
	}
}
